//
//  AccountLoginController.m
//  DianDangDai
//
//  Created by bhf on 2017/12/15.
//  Copyright © 2017年 bhf. All rights reserved.
//

#import "AccountLoginController.h"
#import "ForgetPasswordViewController.h"
@interface AccountLoginController ()
@property (nonatomic, assign) BOOL selected;
@property (nonatomic, assign) BOOL selected2;
@end

@implementation AccountLoginController

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
    _selected = NO;
    _selected2 = YES;
    // Do any additional setup after loading the view.
}

- (void)setupViews {
    self.login.layer.cornerRadius= self.login.height/2;
    self.messageLogin.layer.cornerRadius = self.messageLogin.height/2;
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入用户名/手机号码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_account.font}];
    _account.attributedPlaceholder = attrString;
    NSAttributedString *attrString2 = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_password.font}];
    _password.attributedPlaceholder = attrString2;
    
    
    NSAttributedString *attrString3 = [[NSAttributedString alloc] initWithString:@"请输入手机号码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_phoneNumber.font}];
    _phoneNumber.attributedPlaceholder = attrString3;
    
    NSAttributedString *attrString4 = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_code.font}];
    _code.attributedPlaceholder = attrString4;
    self.navigationItem.backBarButtonItem = BarButtonItem;
    
    _account.text = USER_ACCOUNT;
    _phoneNumber.text = USER_ACCOUNT;
    
    [_password addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_code addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
}
//密码是否可见
- (IBAction)lookPwd:(UIButton *)sender {
    if (_selected == NO) {
        [sender setImage:[UIImage imageNamed:@"zhengyan"] forState:UIControlStateNormal];
        [_password setSecureTextEntry:NO];
        _selected = YES;
    } else {
        [sender setImage:[UIImage imageNamed:@"biyan"] forState:UIControlStateNormal];
        [_password setSecureTextEntry:YES];
        _selected = NO;
    }
   
}
//记住手机号
- (IBAction)savePhoneNumber:(UIButton *)sender {
    if (_selected2 == YES) {
        [_checked setImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
        _selected2 = NO;
    } else {
        [_checked setImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
        _selected2 = YES;
    }
    
}

//忘记密码
- (IBAction)forgetPwd:(UIButton *)sender {
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
    UIViewController *fpvc = [board instantiateViewControllerWithIdentifier:@"fpvc"];
    NSLog(@"%@",self.navigationController);
    [self.navigationController pushViewController:fpvc animated:YES];
    
}

//登录
- (IBAction)login:(UIButton *)sender {
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1013&name=%@&pwd=%@&deviceType=2",API_LOGIN_URL_STRING,self.account.text,self.password.text];
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        [self.view makeToast:dict[@"msg"]];
        NSInteger code = [dict[@"code"] integerValue];
        NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
        if (code == 0) {
            
            [df synchronize];
            [df setObject:dict forKey:@"userInformation"];
            [df setObject:dict[@"username"] forKey:@"userName"];
            [df setObject:dict[@"sign"] forKey:@"userKey"];
            [df setObject:@"Yes" forKey:@"login"];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TabBar" bundle:[NSBundle mainBundle]];
                UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"RootTabBar"];
                
                [self presentViewController:vc animated:YES completion:nil];
            });
            
        } else {
            [df setObject:@"No" forKey:@"login"];
        }
 
    } failure:^(NSError *error) {
        
    } showHUD:YES];
    
}
- (IBAction)getMessage:(UIButton *)sender {
    
    __block int timeout= 119; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"获取验证码" forState:0];
                [sender setTitleColor:[UIColor colorWithHex:@"#FDDC00"] forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
            
        }else{
            
            //            int minutes = timeout / 60;
            
            int seconds = timeout % 120;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [sender setTitle:[NSString stringWithFormat:@"%@S后获取",strTime] forState:UIControlStateNormal];
          
                sender.userInteractionEnabled = NO;
                
            });
            
            timeout--;
            
        }
        
    });
    
    dispatch_resume(_timer);
    
    NSString *urlString = [NSString stringWithFormat: @"%@OPT=1014&mobile=%@",API_LOGIN_URL_STRING,_phoneNumber.text];
    NSLog(@"%@",urlString);
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
         [self.view makeToast:dict[@"msg"]];
    } failure:^(NSError *error) {
        
    } showHUD:YES];
    
    
    
    
}
    
- (IBAction)mssageLogin:(UIButton *)sender {
    
    NSString *urlString = [NSString stringWithFormat: @"%@OPT=1015&name=%@&smsCode=%@&deviceType=1",API_LOGIN_URL_STRING,_phoneNumber.text,_code.text];
    NSLog(@"%@",urlString);
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        [self.view makeToast:dict[@"msg"]];
        NSInteger code = [dict[@"code"] integerValue];
        NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
        if (code == 0) {
            
            [df synchronize];
            [df setObject:dict forKey:@"userInformation"];
            [df setObject:dict[@"username"] forKey:@"userName"];
            [df setObject:dict[@"sign"] forKey:@"userKey"];
            [df setObject:@"Yes" forKey:@"login"];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TabBar" bundle:[NSBundle mainBundle]];
                UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"RootTabBar"];
                
                [self presentViewController:vc animated:YES completion:nil];
            });
            
        } else {
            [df setObject:@"No" forKey:@"login"];
        }
    } failure:^(NSError *error) {
        
    } showHUD:YES];
    
}

//跳转短信登录
- (IBAction)msgLogin:(UIButton *)sender {
    _msgView.hidden = NO;
    _pwdView.hidden = YES;
    [_password resignFirstResponder];
    [_account resignFirstResponder];
}
- (IBAction)pwdLogin:(UIButton *)sender {
    _msgView.hidden = YES;
    _pwdView.hidden = NO;
    [_code resignFirstResponder];
    [_phoneNumber resignFirstResponder];
}

//跳转注册
- (IBAction)regist:(UIButton *)sender {
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
    UIViewController *vc = [board instantiateViewControllerWithIdentifier:@"regist"];
    [self showViewController:vc sender:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TextField

-(void)textFieldDidChange :(UITextField *)theTextField{
    NSLog(@"11111");
    
    if ([theTextField isEqual:_password]) {
        if (theTextField.text.length>5) {
            _login.alpha = 1.0;
            _login.backgroundColor = [UIColor whiteColor];
        } else {
            _login.alpha = 0.5;
            _login.backgroundColor = [UIColor colorWithHex:@"#CCCCCC"];
        }
    }
    if ([theTextField isEqual:_code]) {
        if (theTextField.text.length > 5) {
            _messageLogin.alpha = 1.0;
            _messageLogin.backgroundColor = [UIColor whiteColor];
        } else {
            _messageLogin.alpha = 0.5;
            _messageLogin.backgroundColor = [UIColor colorWithHex:@"#CCCCCC"];
        }
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
